#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int** genArr(int n) {
    assert(n > 0);

    int** arr = (int**)calloc(n, sizeof(int*));
    for (int i = 0; i < n; i++) {
        arr[i] = (int*)calloc(n, sizeof(int));
    }
    return arr;
}

int** LatinSquare(int n) {
    int** arr = genArr(n);

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            arr[i][j] = j + 1 + i;
            if (arr[i][j] > n) {
                arr[i][j] %= n;
            }
        }
    }
    return arr;
}

typedef struct Node {
    int data;
    struct Node* next;
} Node, *LinkedList;

int** LatinSquare2(int n) {
    assert(n > 0);
    LinkedList list = NULL;
    Node* head = NULL;
    Node* curr = NULL;
    Node* tmp;
    int i, j;

    for (int i = 0; i < n; i++) {
        tmp = (Node*)calloc(1, sizeof(Node));
        tmp->data = i + 1;
        if (!head) {
            head = tmp;
        } else {
            curr->next = tmp;
        }
        curr = tmp;
    }
    curr->next = head;
    list = head;

    curr = head;
    int** arr = genArr(n);

    for (i = 0; i < n; ++i, curr = curr->next) {
        for (j = 0; j < n; ++j) {
            int start = curr->data + j; // 第i行开始元素的值
            arr[i][j] = start > n ? start % n : start;
        }
    }

    tmp = list;
    for (int i = 0; i < n; i++) {
        Node* next = tmp->next;
        free(tmp);
        tmp = next;
    }
    list = NULL;

    return arr;
}

int main() {
    int num = 4;
    int** arr = LatinSquare(num);

    for (int i = 0; i < num; i++) {
        for (int j = 0; j < num; j++) {
            printf("%2d", arr[i][j]);
        }
        printf("\n");
    }

    if (arr) {
        for (int i = 0; i < num; i++) {
            if (arr[i]) {
                free(arr[i]);
            }
        }
        free(arr);
    }
    return 0;
}
